import sublime, sublime_plugin
import re
import os
import traceback
# try:
#     from .Edit import Edit as Edit
# except:
#     from Edit import Edit as Edit
DEBUG = True

lua_function_pat = ".*\(.*(?:(?P<self>self.)){1}(?:(?P<varname>[a-zA-Z0-9_$]+))"
lua_function_pat = re.compile(lua_function_pat)


def matchdict(text):
    m = lua_function_pat.match(text)
    if m:
        return m.groupdict()
    else:
        return {}

def getSelections(view):
    position = 0
    selected = []
    sels     = view.sel()

    for sel in sels:
        lineRegions = view.lines(sel)
        for lineRegion in lineRegions:
            position = max(position, lineRegion.end())
            selected.extend(view.substr(lineRegion).split("\n"))

    selection_matches = []
    for line in selected:
        md = matchdict(line)
        if DEBUG:
            print(md,line,"--------")
        if md.get("self", None) is not None: # Make sure it's private or protected
            selection_matches.append(md)
    return {"position": position, "selections": selection_matches}
class InsertNumberCbCommand(sublime_plugin.TextCommand):
    def run(self, edit, text):
        selections = getSelections(self.view)
        file_name = self.view.file_name()
        base_name = os.path.basename(file_name).replace(".lua","")
        if DEBUG:
            print(file_name)
            print(base_name)
        if text is not None and text != "":
            selection_matches = selections["selections"]
            region = self.view.find("return " + base_name,0)
            selection_matches = selections["selections"]
            properties = []
            insert_position = selections["position"]
            if region is not None:
                insert_position = region.begin()
            func_arr = []
            functionTemplate = """function {0}:{1}({2})"""
            if(len(selection_matches) == 0):
                sublime.message_dialog("选择的代码不存在成员方法，无法创建成员函数")
                return
            for prop in selection_matches:
                argsCount = int(text)
                args = []
                for i in range(argsCount):
                    args.append("args" + str(i))

                func = functionTemplate.format(base_name, prop['varname'],",".join(args))
                print(func,self.view.find(func,0).begin() == -1)
                if self.view.find(func,0).begin() == -1:
                    func_arr.append(func + "\n\nend\n")
                else:
                    sublime.message_dialog(func + "函数已经存在,无需重复创建")
            try:
                # edit = self.view.begin_edit('lua_setter_getter',insert_position)
                properties_text = "\n" + "\n".join(func_arr)
                print(properties_text)
                insert_count = self.view.insert(edit, insert_position, properties_text)
                self.view.sel().clear()
                self.view.sel().add(sublime.Region(insert_position, (insert_position + insert_count)))
            except Exception as ex:
                if DEBUG:
                    print(ex)
            finally:
                self.view.end_edit(edit)
class LuaFunctionCallback(sublime_plugin.TextCommand):
    def on_done(self, query,edit):
        print("on_done",query)
        self.query = query
        self.on_createFunc(edit)
        pass

    def on_change(self, query):
        pass
    def on_cancel(self):
        self.query = ""
        pass
    def run(self, edit):
        selections = getSelections(self.view)
        file_name = self.view.file_name()
        self.base_name = os.path.basename(file_name).replace(".lua","")
        if DEBUG:
            print(file_name)
            print(self.base_name)
        self.view.window().show_input_panel('请输入参数个数', '0', lambda text: self.view.run_command('insert_number_cb', {"text": text}), self.on_change, self.on_cancel)
